Site logo

Convert an image file to Base64

Encode by Marc Autret

var base64Encode = function F(/*str*/s)
//--------------------------------------
 {
    var ALPHA = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
 
    var n = s.length,
        a = [], z = 0, c = 0,
        b, b0, b1, b2;
 
    while( c < n )
        {
        b0 = s.charCodeAt(c++);
        b1 = s.charCodeAt(c++);
        b2 = s.charCodeAt(c++);
 
        var b = (b0 << 16) + ((b1 || 0) << 8) + (b2 || 0);
 
        a[z++] = ALPHA.charAt((b & (63 << 18)) >> 18);
        a[z++] = ALPHA.charAt((b & (63 << 12)) >> 12);
        a[z++] = ALPHA.charAt(isNaN(b1) ? 64 : ((b & (63 << 6)) >> 6));
        a[z++] = ALPHA.charAt(isNaN(b2) ? 64 : (b & 63));
        }
 
    s = a.join('');
    a.length = 0;
    a = null;
    return s;
};
 
var fileToBase64 = function(/*File|str*/f)
//--------------------------------------
{
    var s = null;
 
    if( f && (f = new File(f)) && (f.encoding='BINARY') && f.open('r') )
        {
        s = f.read();
        f.close();
        }
 
    return s && base64Encode(s);
};
 
// Client code
// ---
var b64 = fileToBase64("my/path/to/image.jpg");

Decode by Marc Autret

var base64Decode = function F(/*str*/s)
{
    var ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    
    F.cache || F.cache = {
        RE_NON_ALPHA: new RegExp('[^' + ALPHA + ']'),
        RE_BAD_EQUALS: /\=([^=]|\=\=)/ 
        };
 
    if( (n % 4) || F.cache.RE_NON_ALPHA.test(s) || F.cache.RE_BAD_EQUALS.test(s) )
        {
        throw Error("Invalid Base64 data");
        }
 
    var    fChr = String.fromCharCode,
        n = s.length >>> 0,
        a = [],
        c = 0,
        i0, i1, i2, i3,
        b, b0, b1, b2;
 
    while( c < n )
        {
        i0 = ALPHA.indexOf(s[c++]);
        i1 = ALPHA.indexOf(s[c++]);
        i2 = ALPHA.indexOf(s[c++]);
        i3 = ALPHA.indexOf(s[c++]);
        
        b = (i0 << 18) + (i1 << 12) + ((i2 & 63) << 6) + (i3 & 63);
        b0 = (b & (255 << 16)) >> 16;
        b1 = (i2 == 64) ? -1 : (b & (255 << 8)) >> 8;
        b2 = (i3 == 64) ? -1 : (b & 255);
 
        a[a.length] = fChr(b0);
        if( 0 <= b1 ) a[a.length] = fChr(b1);
        if( 0 <= b2 ) a[a.length] = fChr(b2);
        }
 
    // Cleanup and return
    // ---
    s = a.join('');
    a.length = 0;
    a = fChr = null;
    return s;
};

base64.js by David Lindquis.

Link to the thread is here